Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Increasing Order Search Tree

Problem Statement

Given a root node of the binary search tree, rearrange the BST in in-order such that left-most node becomes the root node of the tree, and each node has only one right child but no left child.

Examples

Example 1:

  • Input: root = [2,1,4,null,null,3]
Image
  • Expected Output: [1,null,2,null,3,null,4]
  • Justification: The original tree has the root at 2, with 1 as the left child and a subtree rooted at 4 with 3 as its left child. The rearranged tree starts with 1, then proceeds to 2, followed by 3, and ends with 4, each as the right child of the previous.

Example 2:

  • Input: root = [3,2,5,1,null,4,6]
  • Expected Output: [1,null,2,null,3,null,4,null,5,null,6]
  • Justification: Starting from 1 (the smallest value), each node is connected to the next higher value as its right child until the highest value, 6, is reached.

Example 3:

  • Input: root = [1,null,2,null,3,null,4,null,5]
  • Expected Output: [1,null,2,null,3,null,4,null,5]
  • Justification: The input tree is already a right-skewed tree representing an ascending order sequence. Therefore, the output remains the same as the input.

Solution

To solve this problem, we'll employ an in-order traversal approach, which naturally visits the nodes of a BST in ascending order. This traversal will help us rearrange the tree by ensuring that each node we visit is placed as the right child of the previously visited node. The key here is to maintain a pointer to the last node we've rearranged so we can easily append the next node in order. This approach is effective because it leverages the sorted property of BSTs and allows us to transform the tree in-place, ensuring space efficiency.

Initially, we'll start with a dummy node as a precursor to the first node in our rearranged tree, which simplifies the process of connecting the nodes. As we perform the in-order traversal, we'll continuously update the right child of the last node to point to the current node, effectively "flattening" the tree into a single rightward path. This method is the most effective because it does not require additional space for node storage, and it directly constructs the final structure during the traversal.

Step-by-step Algorithm

  1. Initialize a Dummy Node: Start by creating a dummy node. This node acts as a placeholder to simplify the process of attaching nodes in increasing order. Its right child will eventually point to the smallest element in the tree, marking the beginning of our transformed tree.

  2. In-Order Traversal Setup: Prepare to perform an in-order traversal of the BST. This type of traversal visits nodes in ascending order, which aligns perfectly with our goal of rearranging the tree.

  3. Traversal and Transformation:

    • Visit Left: Recursively visit the left child of the current node. This step ensures that we start with the smallest element.
    • Rearrange Nodes: After visiting the left child, perform the following for the current node:
      • Detach the left child by setting currentNode.left to null. This step is crucial as we're transforming the BST into a structure where each node only has a right child.
      • Attach the current node to the right of the last node processed. This is done by setting lastNode.right to the current node.
      • Update lastNode to the current node, preparing it to attach the next node in sequence.
    • Visit Right: Recursively visit the right child of the current node to continue the in-order traversal.
  4. Finalize the Transformation: After the traversal is complete, the right child of the dummy node points to the smallest element, and all subsequent elements are attached as right children in increasing order. Return dummy.right as the new root of the transformed tree.

Algorithm Walkthrough

Let's consider the input [3,2,5,1,null,4,6]

    3
   / \
  2   5
 /   / \
1   4   6

Step-by-Step Transformation:

  1. Initialize Dummy Node: Create a dummy node. This node serves as a starting point for rearranging the tree.

  2. Start In-Order Traversal:

    • Begin with the root node (3).
  3. Visit Left Subtree of 3:

    • Move to node 2.
    • Visit left subtree of 2, which is node 1.
  4. Process Node 1:

    • Node 1 has no left child, so we start the rearrangement here.
    • Detach left child (none in this case).
    • Attach node 1 to the right of the dummy node.
    • Update lastNode to node 1.
  5. Back to Node 2:

    • Detach left child (previously node 1).
    • Attach node 2 to the right of node 1 (the current lastNode).
    • Update lastNode to node 2.
  6. Proceed to Root Node 3:

    • Node 3's left child (node 2) has been fully processed.
    • Detach left child (node 2 is now attached to the transformed tree, not directly as a left child).
    • Attach node 3 to the right of node 2 (the current lastNode).
    • Update lastNode to node 3.
  7. Visit Right Subtree of 3:

    • Move to node 5.
    • Visit left subtree of 5, which is node 4.
  8. Process Node 4:

    • Node 4 has no left child.
    • Detach left child (none).
    • Attach node 4 to the right of node 3 (the current lastNode).
    • Update lastNode to node 4.
  9. Back to Node 5:

    • Detach left child (node 4 is now part of the transformed tree).
    • Attach node 5 to the right of node 4.
    • Update lastNode to node 5.
  10. Visit Right Subtree of 5:

    • Move to node 6.
    • Process node 6 similarly, attaching it to the right of node 5.

Final Transformed Tree:

The final tree, starting from dummy.right, follows a straight path: 1 -> 2 -> 3 -> 4 -> 5 -> 6.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

: Each node in the binary search tree (BST) is visited exactly once during the in-order traversal, where n is the number of nodes in the tree. Since we perform constant time operations for each node (reassigning pointers), the total time complexity is linear with respect to the number of nodes in the BST.

Space Complexity

: The space complexity is determined by the height of the tree due to the recursion stack during the in-order traversal, where h is the height of the BST.

Increasing Order Search Tree (easy)
Largest Odd Number in String (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis